package com.gxuwz.zhangjiahui.interceptor;

import com.gxuwz.zhangjiahui.entity.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

// 拦截器
public class AdminInterceptor implements HandlerInterceptor {

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        //System.out.println("执行了TestInterceptor的preHandle方法");
        try {
            //统一拦截（查询当前session是否存在user）(这里user会在每次登陆成功后，写入session)
            System.out.println("===============拦截器开始==============");
            User user = (User)request.getSession().getAttribute("user");
            // 判断是否存在用户
            if(user == null){
                System.out.println("===============拦截器结束-true0==============");
                request.getRequestDispatcher("/login").forward(request, response);
                return false;
            }

            String[] limits = (String[])request.getSession().getAttribute("limits");
            if(handler instanceof HandlerMethod) {
                Object bean = ((HandlerMethod) handler).getBean();
                Class<?> beanType = ((HandlerMethod) handler).getBeanType();
                Method method = ((HandlerMethod) handler).getMethod();
                System.out.println("***当前的类："+ bean.getClass().getSimpleName());
                System.out.println("***当前的路径："+ request.getRequestURL());
                // method.getName() 获取当前拦截的方法
                System.out.println("*****当前的方法："+ method.getName());
                // 对用户权限进行判断
                if(method.getName() != "login.action" && limits != null){
                    int num = 0;
                    for (int i = 0; i < limits.length; i++) {
                        if (limits[i].equals(method.getName())) {
                            System.out.println("===============拦截器结束-true1==============");
                            num = 1;
                            return true;
                        }
                    }
//                    // 把对应方法的类获取出来
//                    String nameClass = bean.getClass().getSimpleName();
//                    if(nameClass.indexOf("Ho") != -1){
//                        nameClass = nameClass.replaceAll("Ho","");
//                        System.out.println("nameClass = " + nameClass);
//                    }
//                    String nameController1 = nameClass.replaceAll("Controller","");
//                    // 小写转换
//                    String nameController2 = nameController1.toLowerCase();
//                    System.out.println("nameController1 = " + nameController1);
//                    System.out.println("nameController2 = " + nameController2);
//                    request.setAttribute("result4", "jurisdiction");
                    if(num == 0){
                        // 跳转到欢迎页面
                        request.getSession().setAttribute("result", "jurisdiction");
                        request.getRequestDispatcher("/errorNow").forward(request, response);
                    }
                    return false;
                }
                RequestMapping methodAnnotation = ((HandlerMethod) handler).getMethodAnnotation(RequestMapping.class);
                String[] value = methodAnnotation.value();
                System.out.println(value.toString());
            }
            if(user != null){
                System.out.println("===============拦截器结束-true2==============");
                return true;
            }
            request.getRequestDispatcher("/login").forward(request, response);
        } catch (IOException | ServletException e) {
            e.printStackTrace();
        }
        System.out.println("===============拦截器结束-false==============");
        return false;//如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        //System.out.println("执行了TestInterceptor的postHandle方法");
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // System.out.println("执行了TestInterceptor的afterCompletion方法");
    }

}